package com.example.test3;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class GetCSVData implements InitializingBean {
//    确保程序启动时获取一次统计数据
    @Override
    public void afterPropertiesSet() throws Exception {
        getData();
        System.out.println("程序启动时执行");
    }

//    设置计划任务功能定时更新数据
    @Scheduled(cron = "0 0 7 * * *")
    public static List<RegionStates> getData() throws IOException {
        //爬取CSV文件
        String url = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(url))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();

        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        InputStream inputStream = body.getInputStream();
        Reader reader = new InputStreamReader(inputStream);

//        数据解析
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
        List<RegionStates> list = new ArrayList<>();
        for(CSVRecord csvRecord : records){
            ChangeRecord.change(list,csvRecord);
        }
        System.out.println("--------成功获取CSV数据--------");
        return list;
    }
}
